package blog

import (
	"encoding/json"
	"time"

	"gitee.com/LangHuaHuachihua/blog-go/common"
)

//构造函数声明，增加程序可扩展性,可以扩展字段，可以初始化变量防止 变量 nil 结构体变更构造函数可以变更 修改的地方少

func NewBlog(req *CreateBlogRequest) *Blog {
	return &Blog{
		Meta:              NewMeta(),
		CreateBlogRequest: req,
	}
}

func NewMeta() *Meta {
	return &Meta{
		CreateAt: time.Now().Unix(),
	}
}

// 用户传值时不给参数也有值
func NewCreateBlogRequest() *CreateBlogRequest {
	return &CreateBlogRequest{Tags: map[string]string{}}
}

type Blog struct {
	*Meta
	*CreateBlogRequest
}
type BlogSet struct {
	Total int64   `json:"total"`
	Items []*Blog `json:"items"`
}

func (s *BlogSet) String() string {
	//带格式的json  MarshalIndent
	dj, _ := json.MarshalIndent(s, "", "   ")
	return string(dj)
}

func NewBlogSet() *BlogSet {
	return &BlogSet{
		Items: []*Blog{},
	}
}

// gorm 对应表名定义
func (b *Blog) TableName() string {
	return "blogs"
}

type Meta struct {
	Id        int   `json:"id"`
	CreateAt  int64 `json:"created_at" gorm:"column:created_at"`
	UpdateAt  int64 `json:"updated_at" gorm:"column:updated_at"`
	PublishAt int64 `json:"published_at" gorm:"column:pulished_at"`
}

type CreateBlogRequest struct {
	Title   string `json:"title" validate:"required"`
	Author  string `json:"author" validate:"required"`
	Content string `json:"content" validate:"required"`
	//直接在库里存为json
	Tags   map[string]string `json:"tags" gorm:"serializer:json" `
	Status STATUS            `json:"status" `
}

func NewQueryBlogRequest() *QueryBlogRequest {
	return &QueryBlogRequest{
		PageSize:   20,
		PageNumber: 1,
	}
}

// 默认有分页，模糊搜索，条件过滤
type QueryBlogRequest struct {
	PageSize   int    `json:"page_size"`
	PageNumber int    `json:"page_number"`
	Keywords   string `json:"keywords"`
	Author     string `json:"author"`
}

// 计算offset
func (q *QueryBlogRequest) Offset() int {
	return (q.PageNumber - 1) * q.PageSize
}
func (b *QueryBlogRequest) TableName() string {
	return "blogs"
}

type DescribeBlogRequest struct {
	Title string `json:"title"`
}

type UpdateBlogRequest struct {
}

type DeleteBlogRequest struct {
}

// go get github.com/go-playground/validator/v10
func (req *CreateBlogRequest) Validate() error {
	//校验规则`  `

	return common.Validate(req)
}
